package cn.basic.social.manager.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @ClassName RedisConfig
 * @Description redis配置
 * @Author zlf
 * @Date 2023/9/1 16:11
 */
@Slf4j
public class RedisConfig {

    @ConditionalOnClass(RedisTemplate.class)
    @AutoConfigureBefore(RedisAutoConfiguration.class)
    @ConditionalOnMissingBean(RedisCache.class)
    static class Redis {
        /**
         * 自定义一个redis访问客户端
         * 
         * @author zlf
         * @date 16:13 2023/9/1
         */
        @Bean(name = "socialRedisTemplate")
        public RedisTemplate<String, String> socialRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
            RedisTemplate<String, String> template = new RedisTemplate<>();
            template.setKeySerializer(new StringRedisSerializer());
            template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
            template.setConnectionFactory(redisConnectionFactory);
            return template;
        }

        /**
         * 初始化一个redisCache，后续使用redisCache进行缓存操作
         * 
         * @author zlf
         * @date 16:33 2023/9/1
         */
        @Bean
        public RedisCache redisCache(RedisTemplate<String, String> socialRedisTemplate) {
            return new RedisCache(socialRedisTemplate);
        }
    }

}
